"use strict";
const CompressionPlugin = require("compression-webpack-plugin"); //压缩成gzip包 解决打包后文件过大的问题
//@csdn: webpack.TerserWebpackPlugin、webpack.UglifyjsWebpackPlugin和ParallelUglifyPlugin 区别
//https://blog.csdn.net/qq_29722281/article/details/109489930
// let UglifyjsWebpackPlugin = require("uglifyjs-webpack-plugin");
const TerserPlugin = require("terser-webpack-plugin");
const path = require("path");
const defaultSettings = require("./src/settings.js");

const { NODE_ENV } = process.env;
//测试环境和开发环境
const devEnvs = ["cn-pre", "development"];

function resolve(dir) {
  return path.join(__dirname, dir);
}
function getPlugins() {
  let plugins = [
    new CompressionPlugin(), //压缩成gzip包
  ];
  return plugins;
}
const _VERS = new Date().getTime();

const name = defaultSettings.title; // page title
// If your port is set to 80,
// use administrator privileges to execute the command line.
// For example, Mac: sudo npm run
// You can change the port by the following methods:
// port = 9528 npm run dev OR npm run dev --port = 9528
const port = process.env.port || process.env.npm_config_port || 9528; // dev port

// All configuration item explanations can be find in https://cli.vuejs.org/config/
module.exports = {
  /**
   * You will need to set publicPath if you plan to deploy your site under a sub path,
   * for example GitHub Pages. If you plan to deploy your site to https://foo.github.io/bar/,
   * then publicPath should be set to "/bar/".
   * In most cases please use '/' !!!
   * Detail: https://cli.vuejs.org/config/#publicpath
   */
  publicPath: "/",
  outputDir: "dist",
  assetsDir: "static",
  // lintOnSave: process.env.NODE_ENV === "development",
  lintOnSave: false,
  productionSourceMap: process.env.NODE_ENV === "development",
  devServer: {
    port: port,
    open: true,
    overlay: {
      warnings: false,
      errors: true,
    },
    proxy: {
      "^/api": {
        // target: "http://10.79.41.45:8098", // cn-pre 物理机
        target: "http://10.133.60.68:8001", // cn-pre odin @date 2022-04-21 @by mathewlijiang
        changeOrigin: true, // 在本地会创建一个虚拟服务端，然后发送请求的数据，并同时接收请求的数据，这样服务端和服务端进行数据的交互就不会有跨域问题
        ws: false, //如果要代理 websockets，配置这个参数
        secure: false, // 如果是https接口，需要配置这个参数
        pathRewrite: {
          // 路径重写，
          "^/api": "/api", // 会将 / 替换为 '',也就是 / 会移除
        },
      },

      "^/touchApi": {
        target: "http://10.162.224.20:8001", // cn-pre 物理机
        // target: "http://localhost:8002",
        // target: "http://pre.t-touch.intra.xiaojukeji.com:8001", // cn-pre 物理机
        changeOrigin: true, // 在本地会创建一个虚拟服务端，然后发送请求的数据，并同时接收请求的数据，这样服务端和服务端进行数据的交互就不会有跨域问题
        ws: false, //如果要代理 websockets，配置这个参数
        secure: false, // 如果是https接口，需要配置这个参数
        pathRewrite: {
          // 路径重写，
          "^/touchApi": "", // 会将 / 替换为 '',也就是 / 会移除
        },
      },
    },
    // before: require("./mock/mock-server.js")
  },
  configureWebpack: {
    // provide the app's title in webpack's name field, so that
    // it can be accessed in index.html to inject the correct title.
    name: name,
    mode: devEnvs.includes(NODE_ENV) ? "development" : "production", //只有是production环境时，TerserPlugin或者UglifyjsWebpackPlugin 插件才能生效
    devtool: process.env.NODE_ENV === "development" ? "source-map" : undefined,
    resolve: {
      alias: {
        "@": resolve("src"),
        api: resolve("src/api"),
        components: resolve("src/components"),
        utils: resolve("src/utils"),
        views: resolve("src/views"),
        styles: resolve("src/styles"),
        common: resolve("src/common"),
      },
    },
    optimization: {
      // 此处添加 移除console.log 和 debugger的代码
      minimizer: [
        //这个插件使用terser来缩小你的JavaScript
        new TerserPlugin({
          terserOptions: {
            ecma: undefined,
            warnings: false,
            parse: {},
            compress: {
              drop_console: true, // 清除 console 语句
              drop_debugger: false, // 清除 debugger 语句
              pure_funcs: ["console.log"], // 移除console
            },
          },
        }),
      ],
    },
    plugins: process.env.NODE_ENV === "development" ? [] : getPlugins(),
  },
  css: {
    extract: false, //css样式的热更新
    sourceMap: true,
    loaderOptions: {
      sass: {
        prependData: `@import "@/styles/variables.scss";`,
      },
    },
  },
  chainWebpack(config) {
    // 清除css，js版本号
    config.output.filename("static/js/[name]." + _VERS + ".js").end();
    config.output.chunkFilename("static/js/[name]." + _VERS + ".js").end();
    // it can improve the speed of the first screen, it is recommended to turn on preload
    config.plugin("preload").tap(() => [
      {
        rel: "preload",
        // to ignore runtime.js
        // https://github.com/vuejs/vue-cli/blob/dev/packages/@vue/cli-service/lib/config/app.js#L171
        fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],
        include: "initial",
      },
    ]);

    // when there are many pages, it will cause too many meaningless requests
    config.plugins.delete("prefetch");

    // set svg-sprite-loader
    config.module.rule("svg").exclude.add(resolve("src/assets/icons")).end();
    config.module
      .rule("icons")
      .test(/\.svg$/)
      .include.add(resolve("src/assets/icons"))
      .end()
      .use("svg-sprite-loader")
      .loader("svg-sprite-loader")
      .options({
        symbolId: "icon-[name]",
      })
      .end();

    config.module
      .rule("")
      .test(/\.md$/)
      .use("html-loader")
      .loader("html-loader")
      .end()
      .use("markdown-loader")
      .loader("markdown-loader")
      .end();

    config.module.rule("svg").exclude.add(resolve("src/icons")).end();
    config.module
      .rule("icons")
      .test(/\.svg$/)
      .include.add(resolve("src/icons"))
      .end()
      .use("svg-sprite-loader")
      .loader("svg-sprite-loader")
      .options({
        symbolId: "icon-[name]",
      })
      .end();

    config.when(process.env.NODE_ENV !== "development", (config) => {
      config
        .plugin("ScriptExtHtmlWebpackPlugin")
        .after("html")
        .use("script-ext-html-webpack-plugin", [
          {
            // `runtime` must same as runtimeChunk name. default is `runtime`
            inline: /runtime\..*\.js$/,
          },
        ])
        .end();
      config.optimization.splitChunks({
        chunks: "all",
        cacheGroups: {
          libs: {
            name: "chunk-libs",
            test: /[\\/]node_modules[\\/]/,
            priority: 10,
            chunks: "initial", // only package third parties that are initially dependent
          },
          elementUI: {
            name: "chunk-elementUI", // split elementUI into a single package
            priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
            test: /[\\/]node_modules[\\/]_?element-ui(.*)/, // in order to adapt to cnpm
          },
          commons: {
            name: "chunk-commons",
            test: resolve("src/components"), // can customize your rules
            minChunks: 3, //  minimum common number
            priority: 5,
            reuseExistingChunk: true,
          },
        },
      });
      // https:// webpack.js.org/configuration/optimization/#optimizationruntimechunk
      config.optimization.runtimeChunk("single");
    });
  },
};
